<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form" v-if="headerShow">
        <a-form size="small" :model="pageData" layout="inline">
          <a-form-item label="报修单号">
            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dropDownData"
              @press-enter="huiche" />
          </a-form-item>
          <a-form-item label="报修日期">
            <a-date-picker popup-container="html" class="bacClass" v-model="dropDownData2"
              style="width: 200px" />至<a-date-picker popup-container="html" class="bacClass" v-model="dropDownData3"
              style="width: 200px" />
          </a-form-item>
          <a-form-item label="报修部门">
            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dropDownData4"
              @press-enter="huiche" />
          </a-form-item>
          <a-form-item label="报修员工">
            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dropDownData5"
              @press-enter="huiche" />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar :items="['查询', '新增', '删除', '提交', '取消提交']" @add="addHandler" @del="deleteHandler" @select="selectHandler"
          @tj="tjs" @qxtj="qxtjs">
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" default-active-key="1">
        <a-tab-pane key="1" title="维修单列表">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
              rowSelection="multiple" @grid-ready="gridReady" style="height: calc(100% - 45px)" :defaultColDef="defaultColDef"
              class="ag-theme-alpine" :rowData="tableDataList" :columnDefs="tc" :localeText="localeText1"
              @columnResized="onColumnResized" @columnMoved="onColumnMoved">
            </AgGridVuesCopys>
            <paginationCopys :page-size-options="pagingList1" :total="fySelet.total" show-total show-jumper show-page-size
              @change="PageSize" @page-size-change="change" style="justify-content: center" :page-size="fySelet.size"
              :current="fySelet.page" />
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </template>

    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :mask-closable="false"
      unmount-on-close popup-container=".arco-tabs-content" height="80%" :visible="showAdd" placement="bottom"
      @cancel="showAdd = false" @ok="addOk">
      <template #title>
        {{ sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="dataForm">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="报修单号" field="repairCode" label-col-flex="80px"
                :rules="[{ required: true, message: '报修单号必填' }]" :validate-trigger="['change', 'blur']">
                <a-input class="bacClass" disabled v-model="dataForm.repairCode" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="报修时间" label-col-flex="80px" field="repairTime"
                :rules="[{ required: true, message: '报修时间必填' }]" :validate-trigger="['change', 'blur']">
                <a-date-picker popup-container="html" class="bacClass" style="width: 200px"
                  v-model="dataForm.repairTime" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="报修部门" field="repairDepId" label-col-flex="80px"
                :rules="[{ required: true, message: '报修部门必填' }]" :validate-trigger="['change', 'blur']">
                <a-cascader ref="corporateRef" class="bacClass" :options="options" :style="{ width: '320px' }"
                  v-model="dataForm.repairDepId" allow-clear @change="bxChanges" popup-container="html" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="报修员工" field="repairStaff" label-col-flex="80px"
                :rules="[{ required: true, message: '报修员工必填' }]" :validate-trigger="['change', 'blur']">
                <a-select popup-container="html" class="bacClass" allow-clear allow-search v-model="dataForm.repairStaff"
                  @click="bxBmSelect" :disabled="dataForm.repairDep == ''">
                  <a-option v-for="item in bxYgList">{{ item.name }} </a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="设备编号" field="facilityCode" label-col-flex="80px"
                :rules="[{ required: true, message: '设备编号必填' }]" :validate-trigger="['change', 'blur']">
                <a-select popup-container="html" class="bacClass" :style="{ width: '320px' }"
                  v-model="dataForm.facilityCode" allow-clear @click="machineNameCodeCx('')" @search="machineNameCodeCx"
                  @change="machineNameCodeChange" allow-create allow-search>
                  <a-option v-for="item in machineNameCode"
                    :value="item.machineCode + '-' + item.machineName + '-' + item.machineTypeName">
                    {{ item.machineCode + ' —— ' + item.machineName }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="设备名称" label-col-flex="80px" field="facilityName"
                :rules="[{ required: true, message: '设备名称必填' }]" :validate-trigger="['change', 'blur']">
                <a-input disabled class="bacClass" v-model="dataForm.facilityName" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="设备类型" field="facilityType" label-col-flex="80px"
                :rules="[{ required: true, message: '设备类型必填' }]" :validate-trigger="['change', 'blur']">
                <!-- <a-select popup-container="html"  class="bacClass" allow-clear allow-search v-model="dataForm.facilityType"
                                    @click="sbSelect">
                                    <a-option v-for="item in sbType">{{
                                        item.typeName
                                    }}
                                    </a-option>
                                </a-select> -->
                <a-input disabled class="bacClass" v-model="dataForm.facilityType" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="维修部门" field="maintainDepID" label-col-flex="80px"
                :rules="[{ required: true, message: '维修部门必填' }]" :validate-trigger="['change', 'blur']">
                <a-cascader ref="corporateRef2" class="bacClass" :options="options2" :style="{ width: '320px' }"
                  v-model="dataForm.maintainDepID" allow-clear @change="wxChanges" popup-container="html" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <!-- <a-col :span="6">
                            <a-form-item label="维修部门负责人" field="maintainDepStaff" label-col-flex="120px"
                                :rules="[{ required: true, message: '维修部门负责人必填' }]" :validate-trigger="['change', 'blur']">
                                <a-select popup-container="html"  class="bacClass" allow-clear allow-search v-model="dataForm.maintainDepStaff"
                                    @click="wxBmSelect" :disabled="dataForm.maintainDep == ''">
                                    <a-option v-for="item in wxYgList">{{
                                        item.name
                                    }}
                                    </a-option>
                                </a-select>
                            </a-form-item>
                        </a-col> -->
            <a-col :span="24">
              <a-form-item label="报修说明" label-col-flex="80px" field="repairRemark"
                :rules="[{ required: true, message: '报修说明必填' }]" :validate-trigger="['change', 'blur']">
                <a-input class="bacClass" v-model="dataForm.repairRemark" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item label="设备故障描述" label-col-flex="120px" field="facilityHitchcause"
                :rules="[{ required: true, message: '设备故障描述必填' }]" :validate-trigger="['change', 'blur']">
                <a-textarea :auto-size="{ minRows: 5, maxRows: 500 }" class="bacClass"
                  v-model="dataForm.facilityHitchcause" allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script setup lang="ts">
import { post, get } from '@/api/http'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'

import { Message, Modal } from '@arco-design/web-vue'
import { baseURL } from '@/api/axios.config'
import { slicing } from '@/utils/caseFrimAndSecRig'
import { pagingList } from '@/api/paging'
import { localeText } from '@/api/aggridZw'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
const headerShow = ref(true)

const pageData: any = reactive({
  dropDownData: '',
  dropDownData2: '',
  dropDownData3: '',
  dropDownData4: '',
  dropDownData5: '',
  showAdd: false,
  sideTitle: '',
  pageLoading: false,
})

const {
  dropDownData,
  dropDownData2,
  dropDownData3,
  dropDownData4,
  dropDownData5,
  showAdd,
  sideTitle,
} = toRefs(pageData)

const dataForm: any = reactive({
  repairCode: '',
  repairTime: '',
  repairDep: '',
  repairStaff: '',
  facilityCode: '',
  facilityName: '',
  facilityType: '',
  maintainDep: '',
  // maintainDepStaff: '',
  repairRemark: '',
  facilityHitchcause: '',
  repairDepId: null, //维修部门id
  maintainDepID: null, //报修部门id
})

function selectList() {
  pageData.pageLoading = true
  updateGridState01()
  post({
    url: 'temRepair/repairSubscribe/findRepairSubscribePage',
    data: {
      page: fySelet.page,
      limit: fySelet.size,
      repairCode: pageData.dropDownData,
      repairDep: pageData.dropDownData4,
      repairStaff: pageData.dropDownData5,
      repairTime: pageData.dropDownData2,
      repairTime2: pageData.dropDownData3,
    },
  })
    .then((res: any) => {
      gridOption.value.setRowData(res.data.list)
      fySelet.total = res.data.total
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

const huiche = () => {
  selectList()
}

const selectHandler = () => {
  fySelet.page = 1
  selectList()
}

const options: any = ref([])
const options2: any = ref([])
let firmId: any

const addHandler = () => {
  for (let i in dataForm) {
    dataForm[i] = ''
  }
  pageData.sideTitle = '新增设备报修单'
  post({
    url: 'org/baCompany/getDepartmentTreeByUser',
  }).then((res: any) => {
    if (res.code == 200) {
      get({
        url: 'temRepair/repairSubscribe/repairCode',
      }).then((res) => {
        dataForm.repairCode = res
      })
      pageData.showAdd = true
      options.value = res.data
    }
  })
  post({
    url: 'org/baCompany/getTreeCompanyOrDepartment',
    data: {
      getDepartment: '',
    },
  }).then((res: any) => {
    if (res.code == 200) {
      options2.value = res.data
    }
  })
  post({
    url: 'admin/acl/user/findUserToken',
  }).then((res: any) => {
    if (res.code == 200) {
      // firmId = res.data.data.firmId
    }
  })
}

const deleteHandler = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    return false
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      pageData.pageLoading = true
      post({
        url: 'temRepair/repairSubscribe/deleteRepairSubscribe',
        data: gridOption.value.getSelectedRows().map((o: any) => {
          return {
            id: o.id,
            deleteState: 1,
          }
        }),
      }).then(({ code, data }: any) => {
        if (code === 200) {
          Message.success({
            content: '删除成功',
            duration: 5000,
          })
          fySelet.page = 1
          selectList()
        } else {
          Message.error({
            content: '删除失败',
            duration: 5000,
          })
        }
      })
    },
  })
}

const tjs = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    return false
  }
  for (let i = 0; i < gridOption.value.getSelectedRows().length; i++) {
    if (gridOption.value.getSelectedRows()[i].workersState == 1) {
      Message.warning('已派工请勿提交')
      return
    }
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认提交选中的数据?',
    onOk() {
      pageData.pageLoading = true
      post({
        url: 'temRepair/repairSubscribe/updateRepairSubscribe',
        data: gridOption.value.getSelectedRows().map((o: any) => {
          return {
            id: o.id,
            judgeState: 1,
            submitType: 1,
          }
        }),
      }).then(({ code, data, message }: any) => {
        if (code === 200) {
          Message.success({
            content: '成功',
            duration: 5000,
          })
          fySelet.page = 1
          selectList()
        } else {
          Message.error({
            content: message,
            duration: 5000,
          })
        }
      })
    },
  })
}

const qxtjs = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    return false
  }
  for (let i = 0; i < gridOption.value.getSelectedRows().length; i++) {
    if (gridOption.value.getSelectedRows()[i].workersState == 1) {
      Message.warning('已派工')
      return
    }
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认取消提交选中的数据?',
    onOk() {
      pageData.pageLoading = true
      post({
        url: 'temRepair/repairSubscribe/updateRepairSubscribe',
        data: gridOption.value.getSelectedRows().map((o: any) => {
          return {
            id: o.id,
            judgeState: 0,
          }
        }),
      }).then(({ code, data }: any) => {
        if (code === 200) {
          Message.success({
            content: '删除成功',
            duration: 5000,
          })
          fySelet.page = 1
          selectList()
        } else {
          Message.error({
            content: '删除失败',
            duration: 5000,
          })
        }
      })
    },
  })
}

const tableDataList: any = ref([])
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}
const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}

const fySelet: any = reactive({
  total: 10,
  size: 10,
  page: 1,
})

const PageSize = (val: any) => {
  fySelet.page = val
  selectList()
}

const change = (val: any) => {
  fySelet.size = val
  selectList()
}

const tc = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  {
    headerName: '报修单号',
    field: 'repairCode',
    // pinned: o['fixed'],
    width: 150,
  },
  {
    headerName: '报修时间',
    field: 'repairTime',
    width: 150,
  },
  {
    headerName: '报修部门',
    field: 'repairDep',
    width: 150,
  },
  {
    headerName: '报修员工',
    field: 'repairStaff',
    width: 150,
  },
  {
    headerName: '设备编号',
    field: 'facilityCode',
    width: 150,
  },
  {
    headerName: '设备名称',
    field: 'facilityName',
    width: 150,
  },
  {
    headerName: '设备类型',
    field: 'facilityType',
    width: 150,
  },
  {
    headerName: '维修部门',
    field: 'maintainDep',
    width: 150,
  },
  // {
  //     headerName: '维修部门负责人',
  //     field: 'maintainDepStaff',
  //     width: 150
  // },
  {
    headerName: '报修说明',
    field: 'repairRemark',
    width: 150,
  },
  {
    headerName: '设备故障描述',
    field: 'facilityHitchcause',
    width: 150,
  },
  {
    headerName: '报修图片详情',
    field: 'reportPictureUrl',
    pinned: 'right',
    width: 200,
    cellRenderer: {
      template: `
            <a-space>
                <a-image v-for="i in states" width="40" :src="i"/>
                <span v-if="states.length == 0">暂无图片</span>    
            </a-space>
            `,
      setup(props: any) {
        return {
          states: props.params.data.reportPictureUrl.map((v: any) => {
            return baseURL + v
          }),
        }
      },
    },
  },
  {
    headerName: '状态',
    field: 'judgeState',
    pinned: 'right',
    width: 150,
    filter: true,
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? '未提交' : params.value == 1 ? '已提交' : ''
      },
    },
    cellRenderer: {
      template: `
            <el-tag type="success" v-if="states == 0">未提交</el-tag>
            <el-tag type="warning"  v-if="states == 1">已提交</el-tag>
            `,
      setup(props: any) {
        return {
          states: props.params.data.judgeState,
        }
      },
    },
  },
  {
    headerName: '操作',
    field: 'slot',
    pinned: 'right',
    width: 120,
    cellRenderer: {
      template: `
            <a-space>
                <a-tag class="tagCss" @click="a" v-if="states!=1">修 改</a-tag>
                <a-tag class="tagCss" @click="b" v-if="states!=0">修 改</a-tag>
            </a-space>
            `,
      setup(props: any) {
        const a = () => {
          updateList(props.params.data) // props.params.data
        }
        const b = () => {
          Message.info('已提交不能修改')
        }
        return {
          a,
          b,
          states: props.params.data.judgeState,
        }
      },
    },
  },
]

const formRef: any = ref()

const addOk = () => {
  delete dataForm.upkeepPictureUrl
  delete dataForm.keepPictureUrl
  if (pageData.sideTitle == '新增设备报修单') {
    formRef.value?.validate().then((err: any) => {
      if (!err) {
        post({
          url: 'temRepair/repairSubscribe/saveRepairSubscribe',
          data: [dataForm],
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('成功')
            pageData.showAdd = false
            selectList()
          } else {
            Message.error(res.message)
          }
        })
      }
    })
  } else {
    formRef.value?.validate().then((err: any) => {
      if (!err) {
        post({
          url: 'temRepair/repairSubscribe/updateRepairSubscribe',
          data: [dataForm],
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('成功')
            pageData.showAdd = false
            selectList()
          } else {
            Message.error(res.message)
          }
        })
      }
    })
  }
}

const corporateRef = ref()
const corporateRef2 = ref()
const bxYgList: any = ref([])
const wxYgList: any = ref([])

const bxChanges = () => {
  nextTick(() => {
    dataForm.repairDep = slicing(corporateRef.value.selectViewValue[0].label)
  })
}

const bxBmSelect = () => {
  post({
    url: 'org/hrEmployee/getList',
    data: {
      deleteState: 0,
      obsoleteState: 0,
      department_id: dataForm.repairDepId,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      bxYgList.value = res.data
    }
  })
}

const wxChanges = () => {
  nextTick(() => {
    dataForm.maintainDep = slicing(corporateRef2.value.selectViewValue[0].label)
  })
}

const wxBmSelect = () => {
  post({
    url: 'org/hrEmployee/getList',
    data: {
      deleteState: 0,
      obsoleteState: 0,
      department_id: dataForm.maintainDepID,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      wxYgList.value = res.data
    }
  })
}

const sbType: any = ref([])

const sbSelect = () => {
  post({
    url: 'aps/dwMachineType/getFieldValue',
    data: {
      typeName: '',
    },
  }).then((res: any) => {
    if (res.code == 200) {
      sbType.value = res.data
    }
  })
}

const machineNameCode: any = ref([])

const machineNameCodeCx = (e: any) => {
  post({
    url: 'aps/dwMachine/getFieldValue',
    data: {
      machineCode: e,
      companyId: firmId,
    },
  }).then(({ data, code }: any) => {
    if (code === 200) {
      machineNameCode.value = data
    }
  })
}

const machineNameCodeChange = (e: any) => {
  dataForm.facilityCode = e.split('-')[0]
  dataForm.facilityName = e.split('-')[1]
  dataForm.facilityType = e.split('-')[2]
}

const updateList = (e: any) => {
  for (let i in e) {
    if (i != 'reportPictureUrl') {
      dataForm[i] = e[i]
    }
  }
  pageData.sideTitle = '修改设备报修单'
  post({
    url: 'org/baCompany/getDepartmentTreeByUser',
  }).then((res: any) => {
    if (res.code == 200) {
      get({
        url: 'temRepair/repairSubscribe/repairCode',
      }).then((res) => {
        dataForm.repairCode = res
      })
      pageData.showAdd = true
      options.value = res.data
    }
  })
  post({
    url: 'org/baCompany/getTreeCompanyOrDepartment',
    data: {
      getDepartment: '',
    },
  }).then((res: any) => {
    if (res.code == 200) {
      options2.value = res.data
    }
  })
  post({
    url: 'admin/acl/user/findUserToken',
  }).then((res: any) => {
    if (res.code == 200) {
      // firmId = res.data.data.firmId
    }
  })
}

const localeText1: any = ref(localeText)
const pagingList1: any = ref(pagingList)
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
  saveOrUpdateGridState01('EquipmentMaintenanceList001', gridOption, colState, tc)
const onColumnMoved = () => {
  saveGridState01()
}
const onColumnResized = () => {
  saveGridState01()
}

onMounted(() => {
  selectHandler()
})
</script>
<style scoped lang="less">
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}
</style>
